//
//  CityChooserViewController.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/12/20.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "CityChooserViewController.h"

#import "CityChooserCell.h"

@interface CityChooserViewController () <UITableViewDelegate, UITableViewDataSource>

/// 模型视图
@property (nonatomic, readonly, strong) CityChooserViewModel* viewModel;

// UI
//@property (weak, nonatomic) UILabel *addressLabel;
@property (nonatomic, readonly, strong) NSArray* tableViews;

//IBOutlet
@property (weak, nonatomic) IBOutlet UILabel* cityNumLabel;
@property (weak, nonatomic) IBOutlet UITableView* leftTableView;
@property (weak, nonatomic) IBOutlet UITableView* rightTableView;

@end

@implementation CityChooserViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(SUViewModel2 *)viewModel
{
    self = [super initWithViewModel:viewModel];
    if (self)
    {
        [self initData];
        [self initLoadForRAC];
        [self initUI];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.hidesBottomBarWhenPushed = YES;
    
    self.title = @"选择城市";
}

- (void)initData
{
    
}

- (void)initLoadForRAC
{
    @weakify(self)
    [[self rac_signalForSelector:@selector(viewDidLoad)] subscribeNext:^(id x) {
        @strongify(self)
        
    }];
}

- (void)initUI
{
    UIButton* finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    finishBtn.frame = (CGRect) {0, 0, 54, 44};
    finishBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn setTitleColor:UIColorHex(#008f58) forState:UIControlStateNormal];
    [finishBtn addTarget:self action:@selector(_onBtnFinish) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:finishBtn];
}

- (NSArray*)tableViews
{
    return @[self.leftTableView, self.rightTableView];
}

- (void)bindViewModel
{
    [super bindViewModel];
    
    @weakify(self)
    
    RACSignal* willAppearSignal = [[self rac_signalForSelector:@selector(viewWillAppear:)] replay];
    RACSignal* didAppearSignal = [[self rac_signalForSelector:@selector(viewDidAppear:)] replay];
    RACSignal* viewDidLayoutSVSignal = [[self rac_signalForSelector:@selector(viewDidLayoutSubviews)] replay];
    
    [willAppearSignal subscribeNext:^(id x) {
        @strongify(self)
        
        UserManagerV2* userMgr = [UserManagerV2 sharedUserManagerV2];
    }];
    
    [didAppearSignal subscribeNext:^(id x)
    {
        @strongify(self)
        
        // ScrollView 内容 未能在此时才约束
        
        //Request
        [self.viewModel.reqProvinceCmd execute:nil];
    }];
    
    [[self rac_signalForSelector:@selector(viewWillDisappear:)] subscribeNext:^(id x) {
        @strongify(self)
        
    }];
    
    [[[[viewDidLayoutSVSignal take:1] zipWith:didAppearSignal] deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self)
        
        //重置 更新 frame
        [self _setupViews];
    }];
    
    RAC(self.cityNumLabel, text) = RACObserve(self.viewModel, cityNum);
}

- (void)_setupViews
{
    @weakify(self);
    
    for (NSInteger index=0; index<2; index++)
    {
        CityChooserTableViewModel* curTableVM = nil;
        if (index == 0)
        {
            curTableVM = self.viewModel.provinceTVM;
        }
        else if (index == 1)
        {
            curTableVM = self.viewModel.cityTVM;
        }
        
        [[[[RACObserve(curTableVM, dataSource) distinctUntilChanged] filter:^BOOL(id value) {
            
            return value != nil;
        }] deliverOnMainThread]
         subscribeNext:^(id x) {
             @strongify(self)
             // 刷新数据
             
             NSArray* curArr = x;
             UITableView* curTableView = index == 0 ? self.leftTableView : self.rightTableView;
             UIImageView* emptyTipView = [curTableView viewWithTag:199];
             emptyTipView.hidden = curArr.count > 0;
             
             [self reloadListData:curTableVM.tag];
         }];
        
        curTableVM.didSelectCommand = curTableVM.selectCmd;
        
        UITableView* tableView = index==0 ? self.leftTableView : self.rightTableView;
        tableView.tag = 10 + index;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.delegate = self;
        tableView.dataSource = self;
        
#ifdef __IPHONE_11_0
        MHAdjustsScrollViewInsets_Never(tableView);
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
#endif
        
        [tableView mh_registerNibCell:[CityChooserCell class]];
        
        UIImage* emptyTipImg = MHImageNamed(@"baocuo");
        UIImageView* emptyTipView = [[UIImageView alloc] initWithImage:emptyTipImg];
        emptyTipView.hidden = YES;
        CGPoint centerPoint = (CGPoint) {self.leftTableView.frame.size.width/2.0f, self.leftTableView.frame.size.height/2.0f + 22.0f};
        CGSize viewSize = (CGSize) {100, emptyTipImg.size.height*100/emptyTipImg.size.width};
        emptyTipView.frame = (CGRect) {centerPoint.x - viewSize.width/2.0f, centerPoint.y - viewSize.height/2.0f, viewSize};
        emptyTipView.tag = 199;
        UILabel* tipLabel = [[UILabel alloc] initWithFrame:(CGRect) {16, viewSize.height + 24, viewSize.width, 24}];
        tipLabel.text = @"暂无记录";
        tipLabel.textColor = UIColorHex(#bbbbbb);
        [emptyTipView addSubview:tipLabel];
        [tableView addSubview:emptyTipView];
    }
}

#pragma mark -- sub class can override it
- (UIEdgeInsets)contentInset
{
    return UIEdgeInsetsMake(64, 0, 0, 0);
}

/// reload tableView data
- (void)reloadListData:(NSInteger)tag
{
    for (UITableView* curTableView in self.tableViews)
    {
        if (curTableView.tag == tag)
        {
            for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
            {
                if (curTVM.tag == tag)
                {
                    NSLog(@"ReloadData dataSource : %d", curTVM.dataSource.count);
                    
                    break;
                }
            }
            
            [curTableView reloadData];
            
            break;
        }
    }
}

/// config  cell
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath
{
    return [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CityChooserCell class])];
}

/// config  data
- (void)configureCell:(CityChooserCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(CityChooserCellModel *)object
{
    /// config data (PS：由于MVVM主要是View与数据之间的绑定，但是跟 setViewModel: 差不多啦)
    [cell bindViewModel:object];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    CityChooserTableViewModel* curTableVM = NULL;
    for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return curTableVM.dataSource ? curTableVM.dataSource.count : 1;
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    CityChooserTableViewModel* curTableVM = NULL;
    for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            curTableVM = curTVM;
            
            break;
        }
    }
    
    if (curTableVM.shouldMultiSections) return [curTableVM.dataSource[section] count];
    
    return curTableVM.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    CityChooserTableViewModel* findTVM = NULL;
    
    for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            findTVM = curTVM;
            
            break;
        }
    }
    
    Class cellClass = [CityChooserCell class];
    
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath];
    
    // fetch object
    id object = nil;
    if (findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.section][indexPath.row];
    if (!findTVM.shouldMultiSections) object = findTVM.dataSource[indexPath.row];
    
    /// bind model
    [self configureCell:(CityChooserCell*)cell atIndexPath:indexPath withObject:(id)object];
    
    return cell;
}

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    /// FIXED : when data is empty ，the backgroundColor is exist
    return .0001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /// 由于使用系统的autoLayout来计算cell的高度，每次滚动时都要重新计算cell的布局以此来获得cell的高度 这样一来性能不好
    /// 所以笔者采用实现计算好的cell的高度
    
    for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (tableView.tag == curTVM.tag)
        {
            return [curTVM.dataSource[indexPath.row] cellHeight];
        }
    }
    
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    // execute commond

    for (CityChooserTableViewModel* curTVM in self.viewModel.tableVMs)
    {
        if (curTVM.tag == tableView.tag)
        {
            [curTVM.didSelectCommand execute:indexPath];

            return;
        }
    }
}

#pragma mark - 监听
- (void)_onBtnFinish
{
    [self.viewModel.finishCmd execute:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 工具

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
